package com.shiliuzi.www.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shiliuzi.www.common.Code;
import com.shiliuzi.www.exception.GlobalException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil<T> {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 有限期存储redis
     * @param key
     * @param target
     * @param timeout
     * @param timeUnit
     */
    public boolean setRedis (String key, T target, Long timeout, TimeUnit timeUnit) {
        try {
            stringRedisTemplate.opsForValue().setIfAbsent(key, mapper.writeValueAsString(target),timeout, timeUnit);
            return true;
        } catch (JsonProcessingException e) {
            throw new GlobalException(Code.SYS_ERR,"系统内部出错！请稍后再试！");
        }
    }

    /**
     * 无限期存储redis
     * @param key
     * @param target
     */
    public boolean setRedis (String key, T target) {
        try {
            this.setRedis(key,target,-1l,null);
            return true;
        } catch (Exception e) {
            throw new GlobalException(Code.SYS_ERR,"系统内部出错！请稍后再试！");
        }
    }

    /**
     * 删除刷新token
     * @param key
     */
    public void delRedis (String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 延长过期时间
     * @param key
     * @param timeout
     * @param timeUnit
     */
    public void expireRedis (String key, Long timeout, TimeUnit timeUnit) {
        stringRedisTemplate.expire(key,timeout,timeUnit);
    }

    /**
     * 获取数据
     * @param key
     * @param className
     * @param <T>
     * @return
     */
    public <T> T getRedis (String key, Class<T> className) {
        try {
            String target = stringRedisTemplate.opsForValue().get(key);
            if (target==null) return null;
            return mapper.readValue(target, className);
        } catch (JsonProcessingException e) {
            throw new GlobalException(Code.SYS_ERR,"redis内部出错！获取信息器宕机！");
        }
    }
}
